<?php 

require('../db/database.php');
session_start(); 

// Login
if(isset($_POST['login']) && isset($_POST['user']) && isset($_POST['passwd'])) {
	// Prevent double log in
	if (isset($_SESSION['session_key'])) {
		$result = db_query("SELECT username FROM session WHERE session_key = '".$_SESSION['session_key']."'");
		$array = db_fetch_array($result);
		if ($array["username"] != "") {		// There is record in db
			$arr = array ('status'=>'You have logged in already', 'success'=> false);
			echo json_encode($arr);
			exit;
		}
	}

	// Check identity
	$result = db_query("SELECT password FROM users WHERE username = '".$_POST['user']."'");
	$array = db_fetch_array($result);
	
	if ($_POST['passwd'] == "" || $_POST['passwd'] != $array['password']) { // Fail
		$arr = array ('status'=>'Login Fail', 'success'=> false);
		echo json_encode($arr);
		exit;
	} else {	// Success
		// Session key generation
		$s_key = generate_session_key();
		
		// Update database, session and cookie
		db_query("INSERT INTO session(session_key, username) VALUES ($s_key, '".$_POST['user']."')");
		$_SESSION['session_key'] = $s_key;
		$_SESSION['username'] = $_POST['user'];
		setcookie("session_key", $s_key, 0, "/");
		
		// Generate response
		$arr = array ('status'=>'Login Success', 'success'=> true);
		echo json_encode($arr);
		exit;
	}
	exit;
}

// Logout
if(isset($_POST['logout'])) {
	check_session_exist();
	
	// Update database
	$result = db_query("SELECT room_id FROM session WHERE session_key = " . $_SESSION['session_key']);
	$row = db_fetch_array($result);
	$room_id = $row["room_id"];
	
	if($room_id != "") {	// Player in a room
		$result = db_query("SELECT count(*) as count FROM session WHERE room_id = $room_id AND ai_flag = 0 AND session_key != ". $_SESSION['session_key']);
		$row = db_fetch_array($result);
		$count = $row["count"];

		if ($count == 0) {	// No one in the game
			$result = db_query("DELETE FROM game_room WHERE room_id = $room_id");
			$result = db_query("INSERT INTO game_room (room_id, room_name) VALUES ($room_id, 'Room $room_id')");
			$result = db_query("DELETE FROM map_status");
			$result = db_query("DELETE FROM card_status");
			
			//Clear AI
			$ai_username_array = get_ai_players_of_room($room_id);
			
			foreach ($ai_username_array as $ai) {
				$result = db_query("DELETE FROM users WHERE username = '$ai' ");
				$result = db_query("DELETE FROM session WHERE username = '$ai' ");
			}
		}
	} else {	// Player not in room
		$result = db_query("DELETE FROM map_status WHERE owner = " . $_SESSION['session_key']);
		$result = db_query("DELETE FROM card_status WHERE owner = " . $_SESSION['session_key']);
	}

	$result = db_query("DELETE FROM session WHERE session_key = " . $_SESSION['session_key']);
	$result = db_query("DELETE FROM message WHERE username = '" . $_SESSION['username'] . "'");
	
	session_destroy();
	
	// Response
	$arr = array ('status'=>"You have logged out", 'success'=> true);
	echo json_encode($arr);
	exit;
}

// Select Room
if(isset($_POST['select_room']) && isset($_POST['room_id'])) {
	check_session_exist();
	
	// Check if room exists
	$result = db_query("SELECT room_id FROM game_room WHERE room_id = " . $_POST['room_id']);
	$array = db_fetch_array($result);
	if ($array['room_id'] == "") {	// Not exist, send err and force quit
		$arr = array ('status'=>'Game room not exist', 'success'=> false);
		echo json_encode($arr);
		exit;
	} 
	
	// Insert room_id to session table
	$result = db_query("UPDATE session SET room_id = ".$_POST['room_id']." WHERE session_key = ". $_SESSION['session_key']);
	
	// Set ready state to 0
	$result = db_query("UPDATE session SET ready = 0, ai_flag = 0 WHERE session_key = " . $_SESSION['session_key']);
	
	$_SESSION['room_id'] = $_POST['room_id'];
	
	// Generate Response
	$str = 'Welcome to game room ' . $_POST['room_id'];
	$arr = array ('status'=>$str, 'success'=> true);
	echo json_encode($arr);
	exit;
}

// Ready
if(isset($_POST['ready'])) {
	check_session_exist();
	update_last_response();
	
	// Check if the game is in start state
	$result = db_query("SELECT status FROM game_room WHERE room_id = ". $_SESSION['room_id']);
	$array = db_fetch_array($result);
	
	if ($array["status"] == 'waiting') {
		$result = db_query("UPDATE session SET ready = ". $_POST['ready'] ." WHERE session_key = " . $_SESSION['session_key']);

		//Check if all ready
		$result = db_query("SELECT COUNT(ready) as count FROM session WHERE ready = 0 AND room_id = ". $_SESSION['room_id']);
		$array = db_fetch_array($result);
		if ($array["count"] == 0) {
			$result = db_query("UPDATE game_room SET status = 'START' WHERE room_id = ". $_SESSION['room_id']);
			$result = db_query("UPDATE session SET ready = 0 WHERE ai_flag != 1 AND room_id = ". $_SESSION['room_id']);
		}
		
		$arr = array ('status'=>'Ready state changed', 'success'=>true);
		echo json_encode($arr);
		
	} else if ($array["status"] == 'START') {
		$arr = array ('status'=>'Game is about to start, change of status not allowed', 'success'=>false);
		echo json_encode($arr);
	}
	
	exit;
}

// Get room ready status
if(isset($_POST['get_room_ready_status'])) {
	check_session_exist();
	update_last_response();
		
	$result = db_query("SELECT username, ready FROM session WHERE room_id = " . $_SESSION['room_id']);
	while($array = db_fetch_array($result)) {
		$username = $array['username'];
		$ready = $array['ready'];
		$response_arr[$username] = $ready;
	}
	
	// Check if all ready
	$result = db_query("SELECT status FROM game_room WHERE room_id = " . $_SESSION['room_id']);
	$array = db_fetch_array($result);
	if ($array['status'] != 'waiting') {
		$response_arr['all_ready'] = "yes";
	}

	echo json_encode($response_arr);
	exit;
}

if(isset($_POST['add_ai_player'])) {
	check_session_exist();
	update_last_response();
	$ai_player = $_POST['add_ai_player'];
	
	do {
		$username = "AI-" . rand(1, 9);
		$result = db_query("SELECT count(*) as count FROM users WHERE username = '$username' ");
		$row = db_fetch_array($result);
	} while($row["count"] >= 1);
	
	$password = rand(0, pow(10, 10));
	$result = db_query("INSERT INTO users VALUES ('$username', '$password')");
	$s_key = generate_session_key();
	$room_id = $_SESSION['room_id'];
	
	// Update database, session and cookie
	db_query("INSERT INTO session(session_key, room_id, last_respond, username, ready, ai_flag) VALUES ($s_key, $room_id, ".time().", '$username', 1, $ai_player)");
	
	//$_SESSION['session_key'] = $s_key;
	//$_SESSION['username'] = $_POST['user'];
	//setcookie("session_key", $s_key, 0, "/");
	
	// Generate response
	$arr = array ('status'=>'AI player added', 'success'=> true);
	echo json_encode($arr);
	exit;
	
}

function check_session_exist() {
	if (!isset($_SESSION['session_key'])) {
		$arr = array ('status'=>'You haven\'t log in yet', 'success'=> false);
		echo json_encode($arr);
		exit;
	}

	$result = db_query("SELECT session_key FROM session WHERE session_key = " . $_SESSION['session_key']);
	$array = db_fetch_array($result);
	if ($array['session_key'] == "") {	
		$arr = array ('status'=>'You haven\'t log in yet', 'success'=> false);
		echo json_encode($arr);
		exit;
	} 
}

function update_last_response() {
	$result = db_query("UPDATE session SET last_respond = ".time()." WHERE session_key = ". $_SESSION['session_key']);
}

function generate_session_key() {
	$is_generated = false;
	while (!$is_generated) {
		srand(time());
		$s_key = rand(0, pow(10, 10));
		
		$result = db_query("SELECT session_key FROM session WHERE session_key = " . $s_key);
		$array = db_fetch_array($result);
		$stored_key = $array['session_key'];
		
		if ($stored_key != $s_key) {
			$is_generated = true;
		}	
	}
	return $s_key;
}

function get_ai_players_of_room($room_id) {
	$ai_username_array = array();
	$result = db_query("SELECT username FROM session WHERE room_id = $room_id");
	while($row = db_fetch_array($result)) {
		$tmp = $row["username"];
		if (substr($tmp, 0, 3) === "AI-" && strlen($tmp) === 4) {
			$ai_username_array[count($ai_username_array)] = $tmp;
		}
	}
	return $ai_username_array;
}

?>